/**
 * @param {number[][]} board
 * @return {number}
 */
var snakesAndLadders = function (board) {

  function positionToMatrix(x) {
    let r = Math.floor((x - 1) / n); //从下向上数第几行，从0开始算
    let c = (x - 1) % n; //从左往右数第几列，从0开始算
    if (r % 2 == 1) c = n - 1 - c; //如果是奇数行，则编号为从右向左，因此正确列为n-1-c
    return [n - 1 - r, c]; //返回真实坐标（即左上角为0，0，右下角为n-1，n-1的常规坐标系）
  }
  let n = board.length;
  let visit = new Array(n * n + 1).fill(false);
  let q = [[1, 0]];
  while (q.length) {
    let [loc, step] = q.shift();
    for (let i = 1; i <= 6; i++) {
      let nx = loc + i;
      if (nx > n * n) break;
      let [r, c] = positionToMatrix(nx);
      if (board[r][c] > 0) nx = board[r][c];
      if (nx == n * n) return step + 1;
      // 需要把记录过的位置过滤掉
      if (!visit[nx]) {
        visit[nx] = 1;
        q.push([nx, step + 1]);
      }
    }
  }
  return -1;
};
let board = [
  [-1, -1, -1, -1, -1, -1],
  [-1, -1, -1, -1, -1, -1],
  [-1, -1, -1, -1, -1, -1],
  [-1, 35, -1, -1, 13, -1],
  [-1, -1, -1, -1, -1, -1],
  [-1, 15, -1, -1, -1, -1]
];
console.log(snakesAndLadders(board));
board = [
  [-1, -1],
  [-1, 3]
];
console.log(snakesAndLadders(board));
